package com.homework.dao;

import com.homework.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import lombok.extern.slf4j.Slf4j; // 引入 Lombok 的 SLF4J 日志注解

@Repository
@Slf4j // 自动注入日志对象
public class UserDao {
    @Autowired
    private Connection conn;

    public int insert(User user) {
        String sql = "INSERT INTO user(user_id, username, password) VALUES (?, ?, ?)"; // 注意添加 user_id
        try (PreparedStatement ps = conn.prepareStatement(sql)) {
            ps.setString(1, user.getUser_id()); // 获取 user_id 值
            ps.setString(2, user.getUsername());
            ps.setString(3, user.getPassword());
            return ps.executeUpdate();
        } catch (Exception e) {
            log.error("Error inserting user: {}", e.getMessage(), e);
        }
        return 0;
    }


    public User login(String name, String password) {
        String sql = "SELECT * FROM user WHERE username = ? AND password = ?";
        try (PreparedStatement ps = conn.prepareStatement(sql)) {
            ps.setString(1, name);
            ps.setString(2, password);
            try (ResultSet rs = ps.executeQuery()) {
                if (rs.next()) {
                    User user = new User();
                    user.setUsername(rs.getString("username"));
                    user.setPassword(rs.getString("password"));
                    return user;
                }
            }
        } catch (SQLException e) {
            log.error("Error logging in user: {}", e.getMessage(), e);
        }
        return null;
    }

    public int countAllUsers() {
        String sql = "SELECT COUNT(*) FROM user";
        try (PreparedStatement ps = conn.prepareStatement(sql)) {
            try (ResultSet rs = ps.executeQuery()) {
                if (rs.next()) {
                    return rs.getInt(1);
                }
            }
        } catch (SQLException e) {
            log.error("Error counting users: {}", e.getMessage(), e);
        }
        return 0;
    }
}